import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken, setRefreshToken, removeRefreshToken } from '@/utils/auth'
import { rootRoute, extraRoutes, notFoundRoute, devRoutes, buildAsyncRoutes, resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  menuData: [],
  asyncRoutesIsLoaded: false
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTES: (state, { asyncRoutes, isLoaded }) => {
    state.asyncRoutesIsLoaded = isLoaded
    // state.menuData = constantRoutes.find((item) => item.path === '/').children.concat(asyncRoutes)
    state.menuData = asyncRoutes
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { name, password, formId, code } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: name.trim(), password, formId, code })
        .then((response) => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          setRefreshToken(data.refreshToken)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response) => {
          const { data } = response
          if (!data) {
            reject('Verification failed, please Login again.')
          }
          const { name, avatar, routes } = data
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          let asyncRoutes = buildAsyncRoutes(routes)

          let children = [...rootRoute.children, ...asyncRoutes]
          if (process.env.NODE_ENV !== 'production') {
            children = [...rootRoute.children, ...devRoutes, ...asyncRoutes]
          }
          // commit('SET_ROUTES', { asyncRoutes, isLoaded: true })
          // resolve([{ ...rootRoute, children: asyncRoutes }])
          commit('SET_ROUTES', { asyncRoutes: children, isLoaded: true })
          resolve([{ ...rootRoute, redirect: children[0].redirect || children[0].path, children: [...children, ...extraRoutes] }, notFoundRoute])
        })
        .catch((error) => {
          console.log(error)
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROUTES', { asyncRoutes: [], isLoaded: false })
          removeToken()
          removeRefreshToken()
          resetRouter()
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_ROUTES', { asyncRoutes: [], isLoaded: false })
      removeToken()
      removeRefreshToken()
      resolve()
    })
  },

  // refresh token
  refreshToken({ commit }, { token, refreshToken }) {
    console.log(refreshToken)
    return new Promise((resolve) => {
      commit('SET_TOKEN', token)
      setToken(token)
      if (refreshToken) {
        setRefreshToken(refreshToken)
      }
      resolve({ token, refreshToken })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
